package com.fdq.dianping.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fdq.dianping.entity.Result;
import com.fdq.dianping.entity.SeckillVoucher;
import com.fdq.dianping.entity.VoucherOrder;
import com.fdq.dianping.entity.dto.UserDto;
import com.fdq.dianping.mapper.VoucherOrderMapper;
import com.fdq.dianping.service.ISeckillVoucherService;
import com.fdq.dianping.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fdq.dianping.service.IVoucherService;
import com.fdq.dianping.util.RedisClient;
import com.fdq.dianping.util.RedisIdGenerator;
import com.fdq.dianping.util.ThreadLocalUtil;
import jakarta.annotation.PostConstruct;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.fdq.dianping.util.Constants.VoucherOrder_Prefix;
import static com.fdq.dianping.util.VocherOrderStatus.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author fdq
 * @since 2024-12-29
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    private IVoucherService voucherService;

    @Resource
    private RedisIdGenerator redisIdGenerator;

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    //用于下单的线程 单线程线程池确保订单处理的顺序性，避免并发问题
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();
    @Autowired
    private RedisClient redisClient;

    /**
     * ToDo:监听消息队列中的订单信息实现异步下单
     */
    // 用于初始化异步订单处理线程
    @PostConstruct //表示在当前类依赖注入完成后执行
    private void init(){
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }

    //处理订单的类（实现线程方法）
    private class VoucherOrderHandler implements Runnable{
        String queueName="stream.orders";
        @Override
        public void run() {
            while (true){
                try {
                    //1.获取消息队列里的订单信息 XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS streams.orders
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(queueName, ReadOffset.lastConsumed())
                    );

                    //2.判断消息获取是否成功
                    if(list.isEmpty() || list == null){
                        //没有消息继续循环
                        continue;
                    }

                    //3.解析消息中的订单信息
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);

                    //4.获取成功下单
                    handleVoucherOrder(voucherOrder);

                    // 5. ACK确认  SACK stream.orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",record.getId());

                } catch (Exception e) {
                    log.error("处理订单异常",e);
                    handelPendingList();
                }
            }
        }

        private void handelPendingList() {
            while (true){
                try {
                    // 1.获取 pending-list 中的订单信息 XREADGROUP GROUP g1 c1 COUNT 1 STREAMS stream.orders 0
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create(queueName, ReadOffset.from("0"))
                    );

                    // 2.判断消息获取是否成功
                    if (list.isEmpty()){
                        // 2.1 如果不存在，获取失败，说明pending-list没有消息,结束循环
                        break;
                    }

                    //3.解析消息中的订单信息
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> values = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(values, new VoucherOrder(), true);

                    // 4 如果获取成功，可以下单
                    handleVoucherOrder(voucherOrder);

                    // 5. ACK确认  SACK stream.orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",record.getId());

                } catch (Exception e) {
                    log.error("处理pending-list异常",e);
                    try {
                        Thread.sleep(20);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }
    }



    //lua脚本
    private final static DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("/lua/seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }


    //成员变量 用于事务
    private IVoucherOrderService proxy;

    @Override
    public Result seckillVoucher(Long voucherId) {
        //获取当前登录用户信息
        Map<String,Object> userMap = ThreadLocalUtil.get();
        UserDto user = BeanUtil.mapToBean(userMap,UserDto.class,true);
        //设置订单id
        long orderId = redisIdGenerator.nextId(VoucherOrder_Prefix);
        //1.执行lua
        Long result = stringRedisTemplate.execute(            //第一个参数是脚本，第二个参数是键列表（lua中的KEYS），剩下的参数全部是值（lua中的ARGV）
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),
                user.getId().toString(),
                String.valueOf(orderId)
        );

        //2.判断结果
        int r = result.intValue();
        if(r != 0){
            //异常
            return Result.error(r == 1 ? "库存不足" : "不能重复下单");
        }

        // 3.获取代理对象
        proxy = (IVoucherOrderService) AopContext.currentProxy();

        return Result.success(orderId);
    }



    //创建订单前加锁
    private void handleVoucherOrder(VoucherOrder voucherOrder){
        //获取用户
        Long userId = voucherOrder.getUserId();
        //创建锁对象
        RLock lock = redissonClient.getLock("lock:order:" + voucherOrder.getVoucherId() + ":" + userId);
        //获取锁
        boolean locked = lock.tryLock();
        if(!locked){
            //获取锁失败
            log.error("获取锁失败");
            return;
        }
        try {
            // 调用下单方法
            proxy.createSeckillVoucherOrder(voucherOrder);
        } finally {
            //释放锁
            lock.unlock();
        }

    }

    //创建秒杀订单
    @Transactional
    public Result createSeckillVoucherOrder(VoucherOrder voucherOrder) {
        // 5. 一人一单
        Long userId = voucherOrder.getUserId() ;

        // 5.1 查询订单,查询当前用户是否已经购买过该优惠券
        int count = query().eq("user_id", userId)
                .eq("voucher_id", voucherOrder.getVoucherId()).count().intValue();

        // 5.2 一人一单 判断
        if (count>0){
            //用户已经购买过了
            log.error("用户已经购买过一次");
            return Result.error("用户已经购买过一次");
        }

        //6.乐观锁扣减库存,确保只有在库存大于0时才能进行扣减，防止超卖
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1") // set stock = stock -1
                .eq("voucher_id", voucherOrder.getVoucherId()).gt("stock",0)// where id =? and stock > 0?
                .update();
        if (!success){
            //扣减失败
            log.error("库存不足");
        }

        // 7.保存订单至数据库
        save(voucherOrder);
        return Result.success();
    }

    /*
* Todo:传统数据库层面的秒杀
* */
//    @Override
//    public Result seckillVoucher(Long voucherId) {
//        //查询优惠券信息
//        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
//        //判断秒杀是否开始
//        if(seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())){
//            return Result.error("秒杀尚未开始");
//        }
//        //判断秒杀是否结束
//        if(seckillVoucher.getEndTime().isBefore(LocalDateTime.now())){
//            return Result.error("秒杀已经结束");
//        }
//
//        //判断库存是否充足
//        Integer stock = seckillVoucher.getStock();
//        if(stock < 1){
//            return Result.error("秒杀券已抢完");
//        }
//        //获取当前登录用户信息
//        Map<String,Object> userMap = ThreadLocalUtil.get();
//        UserDto user = BeanUtil.mapToBean(userMap,UserDto.class,true);
//        //给每个用户加一个悲观锁，这里注意intern方法是按字符串内容获取字符串的地址，可以实现内容相同的字符串返回一样的地址
//        //用户先获取锁再执行事务
//        synchronized (user.getId().toString().intern()){
//            //spring事务是用一个代理对象完成的，这里加锁应该加到代理对象上
//            //获取代理对象
//            IVoucherOrderService proxy =(IVoucherOrderService) AopContext.currentProxy();
//            return proxy.createSeckillVoucherOrder(voucherId, user);
//        }
//
//    }
//
//    @Transactional          //保证更新优惠券表和添加优惠券订单都成功或都失败
//    public Result createSeckillVoucherOrder(Long voucherId, UserDto user){
//        //实现一人一单，判断该用户是否已经买过该秒杀券
//        Long count = query().eq("user_id", user.getId()).eq("voucher_id", voucherId).count();
//        if(count > 0){
//            return Result.error("一名用户只能买一单");
//        }
//
//        //更新库存
//        Boolean success = seckillVoucherService.update().setSql("stock = stock - 1")
//                .eq("voucher_id", voucherId)
//                .gt("stock", 0).update();
//        if(!success){
//            return Result.error("秒杀券全部抢完！");
//        }
//
//        //创建订单
//        VoucherOrder voucherOrder = new VoucherOrder();
//        //设置订单id
//        long orderId = redisIdGenerator.nextId(VoucherOrder_Prefix);
//        voucherOrder.setId(orderId);
//        //设置用户id
//
//        voucherOrder.setUserId(user.getId());
//        //设置优惠券id
//        voucherOrder.setVoucherId(voucherId);
//        //设置订单状态为未支付
//        voucherOrder.setStatus(NotPay);
//        save(voucherOrder);
//        return Result.success(orderId);
//
//    }
    //创建普通优惠券订单
    @Override
    public Result createVoucherOrder(Long voucherId) {
        //获取当前登录用户信息
        Map<String,Object> userMap = ThreadLocalUtil.get();
        UserDto user = BeanUtil.mapToBean(userMap,UserDto.class,true);
        //创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        //设置订单id
        long orderId = redisIdGenerator.nextId(VoucherOrder_Prefix);
        voucherOrder.setId(orderId);
        //设置用户id
        voucherOrder.setUserId(user.getId());
        //设置优惠券id
        voucherOrder.setVoucherId(voucherId);
        boolean save = save(voucherOrder);
        if(save){
            return Result.success(orderId);
        }else {
            return Result.error("购买优惠券失败");
        }

    }


    /**
     * 以下是订单状态修改
     */
    @Override
    public Result refundVoucher(Long voucherOrderId) {
        //查询订单信息
        VoucherOrder voucherOrder = getById(voucherOrderId);
        if(voucherOrder == null){
            return Result.error("不能退款一个不存在的订单");
        }
        voucherOrder.setStatus(Refund);
        voucherOrder.setRefundTime(LocalDateTime.now());
        updateById(voucherOrder);
        return Result.success("订单已退款");
    }

    @Override
    public Result payVoucher(Long voucherOrderId) {
        //查询订单信息
        VoucherOrder voucherOrder = getById(voucherOrderId);
        if(voucherOrder == null){
            return Result.error("不能支付一个不存在的订单");
        }
        voucherOrder.setStatus(Payed);
        voucherOrder.setPayTime(LocalDateTime.now());
        updateById(voucherOrder);
        return Result.success("订单已支付");
    }

    @Override
    public Result useVoucher(Long voucherOrderId) {
        //查询订单信息
        VoucherOrder voucherOrder = getById(voucherOrderId);
        if(voucherOrder == null){
            return Result.error("不能使用一个不存在的订单");
        }
        voucherOrder.setStatus(Used);
        voucherOrder.setUseTime(LocalDateTime.now());
        updateById(voucherOrder);
        return Result.success("订单已核销");
    }

    /*
    * 未支付订单15分钟后转为取消状态，使用定时任务完成
    * */
    // 每5分钟执行一次
    @Scheduled(fixedRate = 5 * 60 * 1000)
    public void cancelUnpaidVoucher() {
        LocalDateTime fifteenMinutesAgo = LocalDateTime.now().minusMinutes(15);
        QueryWrapper<VoucherOrder> voucherOrderQueryWrapper = new QueryWrapper<>();
        voucherOrderQueryWrapper.eq("status", NotPay);
        // 设置查询条件，筛选创建时间早于 15 分钟前的订单
        voucherOrderQueryWrapper.le("create_time", fifteenMinutesAgo);
        List<VoucherOrder> unpaidOrders = list(voucherOrderQueryWrapper);
        unpaidOrders.forEach(voucherOrder -> {
            voucherOrder.setStatus(Cancel);
            updateById(voucherOrder);
        });
    }
}
